package www.lagou.dao;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import www.lagou.entity.Account;
import www.lagou.utils.DruidUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class AccountDao {

    QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
    //控制事物(无法正常控制)
//    Connection connection = DruidUtils.getConnection();

    //自定义成员方法实现转账的操作；
    public boolean zhuanZhang(String card1,String card2,double balance) {
        try {
            //调用方法判断转账方余额是否足够
            if(judgeMoneyByBalance(card1,balance)){
               // connection.setAutoCommit(false);
                String sql1 = "update account set balance = balance - ? where card = ?";
                String sql3 = "insert into transaction (cardid,tratype,tramoney,tradate) velues(?,?,?,?)";
                String sql2 = "update account set balance = balance + ? where card = ?";
                String sql4 = "insert into transaction (cardid,tratype,tramoney,tradate) velues(?,?,?,?)";
                qr.update(sql1,balance,card1);
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                Date date1 = sdf.parse("2021-01-17 09:34:11");
                qr.update(sql3,card1,"转出",balance,"2021-01-17 09:34:11");
                qr.update(sql2,balance,card2);
//                Date date2 = sdf.parse("2021-01-17 10:34:11");
                qr.update(sql4,card2,"转入",balance,"2021-01-17 10:34:11");
                return true;
            }else{
                return false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    //自定义成员方法判断转账方账户是否有足够余额
    public boolean judgeMoneyByBalance(String card,double balance) throws SQLException {
        String sql = "select * from account where card = ?";
        Account account = qr.query(sql, new BeanHandler<Account>(Account.class), card);
        if(account.getBalance() >= balance){
            return true;
        }else {
            return false;
        }
    }


}
